/**
 * 埋点Composable - 提供按钮级PV跟踪能力
 * 使用方式：
 * const { trackButtonClick, trackPageView } = useTracking();
 * 
 * // 在按钮点击时触发
 * <el-button @click="() => {
 *   handleSubmit();
 *   trackButtonClick('submit_button', 'checkout');
 * }">提交</el-button>
 */
export function useTracking() {
  // 基本埋点方法
  const trackEvent = (category: string, action: string, label: string, value: number, customData: any = {}) => {
    if ((window as any).DevOpsBITracker) {
      // 添加时间戳，便于区分相同事件
      const eventData = {
        ...customData,
        timestamp: new Date().toISOString()
      }
      
      ;(window as any).DevOpsBITracker.trackEvent(
        category,
        action,
        label,
        value,
        eventData
      )
      
      // 调试日志
      if (import.meta.env.DEV) {
        console.log('[埋点]', {
          category,
          action,
          label,
          value,
          customData: eventData
        })
      }
    }
  }

  // 按钮点击埋点
  const trackButtonClick = (buttonName: string, pageName: string, extraData: any = {}) => {
    trackEvent('button', 'click', buttonName, 1, {
      page: pageName,
      ...extraData
    })
  }
  
  // 页面访问埋点
  const trackPageView = (pageName: string, extraData: any = {}) => {
    if ((window as any).DevOpsBITracker) {
      ;(window as any).DevOpsBITracker.trackCustomData({
        page: pageName,
        source: document.referrer || 'direct',
        ...extraData,
        timestamp: new Date().toISOString()
      })
    }
  }

  // 表单提交埋点
  const trackFormSubmit = (formName: string, status: string = 'success', extraData: any = {}) => {
    trackEvent('form', 'submit', formName, status === 'success' ? 1 : 0, {
      status,
      ...extraData
    })
  }
  
  // 资源加载埋点
  const trackResourceLoad = (resourceType: string, resourceName: string, status: string, extraData: any = {}) => {
    trackEvent('resource', 'load', `${resourceType}_${resourceName}`, status === 'success' ? 1 : 0, {
      type: resourceType,
      name: resourceName,
      status,
      ...extraData
    })
  }
  
  // 用户操作埋点
  const trackUserAction = (action: string, target: string, extraData: any = {}) => {
    trackEvent('user', action, target, 1, extraData)
  }

  return {
    trackEvent,
    trackButtonClick,
    trackPageView,
    trackFormSubmit,
    trackResourceLoad,
    trackUserAction
  }
}

export default useTracking

